<?php

namespace App\Service\Third;

use App\Amqp\Producer\ProcessImCallbackProducer;
use App\Cache\RedisKey;
use App\Helpers\ImUtil;
use App\Helpers\RedisUtil;
use App\Job\ProcessImCallback;
use App\Model\Service\NewGirlReplyPackageService;
use App\Model\User;
use App\Model\UserMsgLog;
use App\Model\UserProfile;
use App\Service\BaseService;
use Hyperf\Amqp\Producer;
use Hyperf\AsyncQueue\Driver\DriverFactory;
use Hyperf\DbConnection\Db;
use Hyperf\Utils\ApplicationContext;

/**
 * 融云消息回调
 */
class RongCallbackService extends BaseService
{
    function __construct(DriverFactory $driverFactory)
    {
        parent::__construct($driverFactory);
        $this->driverFactory = $driverFactory;
        // $this->queueDriver = $driverFactory->get('default');
    }

    public function handle()
    {
        //处理回调信息
        $this->doProcess();
        return $this->responseJson();
    }

    /**
     * 处理回调信息
     * @param array $callbackInfo
     */
    function doProcess()
    {
        $callbackInfo = $this->request->all();
        if (!in_array($callbackInfo['objectName'], ImUtil::ROUTE_MSG_TYPE)) return;
        // if (isset($callbackInfo['objectName'])) log_info(__CLASS__ . "=={$callbackInfo['objectName']}");
        log_info(__CLASS__ . "==" . json_encode($callbackInfo));
        if (isset($callbackInfo['content'])) {
            //用户收发消息
            if (is_string($callbackInfo['content'])) {
                $callbackInfo['content'] = json_decode($callbackInfo['content'], true);
            }

            $this->addLogs($callbackInfo);

//            $queueKey = 'default';
//            $queDriver = $this->driverFactory->get($queueKey);
//            $queDriver->push(new ProcessImCallback($callbackInfo));

            $processImCallback = new ProcessImCallbackProducer($callbackInfo);
            $producer = ApplicationContext::getContainer()->get(Producer::class);
            $producer->produce($processImCallback);
        }
        return;
    }

    /**
     * 返回指定信息
     */
    function responseJson($statusCode = 0)
    {
        $ret = [
            "ActionStatus" => "OK",
            "ErrorInfo" => "",
            "ErrorCode" => 0 // 0为回调成功，1为回调出错
        ];
        return $ret;
    }

    /**
     * 添加记录
     * @param $callbackInfo
     * @return void
     */
    private function addLogs($callbackInfo)
    {
        $fromImAccount = $callbackInfo['fromUserId'];
        $toImAccount = $callbackInfo['toUserId'];

        $userIds = User::getUserIdByIm([$fromImAccount, $toImAccount]);
        $userId = $userIds[$fromImAccount];
        $chatUserId = $userIds[$toImAccount];

        if (strlen($toImAccount) < 15 || strlen($fromImAccount) < 15) {
            log_info(__CLASS__ . "==Error==From:{$fromImAccount}==To:{$toImAccount}");
            return;
        }
        log_info(__CLASS__ . "==From:{$fromImAccount}==To:{$toImAccount}");

        $info = [
            'from_account' => $fromImAccount,
            'to_account' => $toImAccount,
            'msg_detail' => json_encode($callbackInfo),
            'from_userid' => $userId,
            'to_userid' => $chatUserId,
            'msg_type' => $callbackInfo['objectName'],
            'official' => 0,
        ];
        UserMsgLog::create($info);

        $key = RedisKey::getUserMsgNum($userId);

        $where[] = ['from_userid','=', $userId];

        $redis = RedisUtil::getRedis();

        $userInfo = UserProfile::getProfile($userId);
        if ($userInfo->gender == 0) {
            // 新人回复礼包，女生记录总的发送数
            $redis->zIncrBy($key, 1,0);


            $newGirlTaskValid = config('act.new_girl_task_valid', '2023-03-12');
            if ($userInfo->created_at >= $newGirlTaskValid) {
                NewGirlReplyPackageService::firstReplyReward((int)$userId);
            }

            return;
        }

        $totalNum = 1;
        if (!$redis->exists($key)){
            $totalNum = Db::table('user_msg_log')->where($where)->count();
        }
        $redis->zIncrBy($key, $totalNum,0);

        $num = 1;
        if (!($redis->zScore($key,$chatUserId))){
            $where[] = ['to_userid','=',$chatUserId];
            $num = Db::table('user_msg_log')->where($where)->count() ?? 0;
        }
        $redis->zIncrBy($key,$num,$chatUserId);
    }
}
